// packageE/appointment/technician/work_day/TechnicianTime.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    today: "",
    value: "2018-11-11",
    week: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    lastMonth: "lastMonth",
    nextMonth: "nextMonth",
    selectVal: "",

    showDefault: false,
    show1: false,


    // 工作开始时间和结束时间
    choose_end: "00:00",
    choose_start: "00:00",
    isDefault: 0,
    even_true: false,
    calendarEvents: [],
    default_time: [],
    day_time: [],
    aplly_for: 1,//1-可编辑、2-不可编辑
    aid: "",
    isRest: false,
    imgPath: app.globalData.imgPath,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      aid: options.aid,
      aplly_for:options.aplly_for
    });
    let today = new Date().getFullYear() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getDate();
    this.getData();
    this.getTimeList(new Date(`${today} 00:00:00`).getTime() / 1000);
    this.getDefault();
  },
  delSingle(e){
    if(this.data.aplly_for==-1){
      return;
    }
    let {id:wid} = e.currentTarget.dataset.item;
    app._getNetWork({
      url:app.getNetAddresss("plugin.be-within-call.frontend.work-time.del"),
      data:{wid},
      success:resdata=>{
        let {result,msg}= resdata.data;
        app.tips(msg);
        if(result){
          this.getTimeList(new Date(`${this.data.today} 00:00:00`).getTime() / 1000);
          this.set_calender();
        }
      }
    })
  },
  getTimeList(date) {
    app._getNetWork({
      url: app.getNetAddresss("plugin.be-within-call.frontend.work-time.date-time"),
      data: {
        aid: this.data.aid,
        date
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result) {
          let arr = data;
          if (arr && arr.length !== 0) {
            for (let i = 0; i < arr.length; i++) {
              arr[i].work_hour_start = arr[i].start_at;
              arr[i].work_hour_end = arr[i].finish_at;
              arr[i].need_rest == 1 ? arr[i].status = false : arr[i].status = true;
            }
            let _every = arr.every(item => {
              return item.need_rest == 1;
            })
            if (!_every) {
              this.setData({
                isRest: false
              })
            } else {
              this.setData({
                isRest: true
              })
            }
            this.setData({
              day_time: arr
            })

          } else {
            this.setData({
              day_time: [],
              isRest: false
            })
          }
        } else {
          app.tips(msg);
        }

      }
    })
  },

  getData() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.be-within-call.frontend.work-time.group'),
      data: {
        aid: this.data.aid
      },
      success: resdata => {
        let {
          result,
          data,
          msg
        } = resdata.data;
        if (result) {
          console.log(data, "data");
          let list = data;
          let lis = [];
          list.forEach(item => {
            lis.push(this.timestampToTime(item.date));
          });
          console.log(lis, "lis=====");
          this.setData({
            calendarEvents: lis,
            even_true: true
          });

        } else {
          app.tips(msg);
        }
      }
    })
  },
  timestampToTime(timestamp) {
    if (!Number(timestamp) || timestamp == "") {
      return "";
    }
    let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + "-";
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
    let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
    return Y + M + D;
  },


  // choose(item, key) {
  //   console.log(item);
  //   if (key) {
  //     this.setData({
  //       chooseStore: item,
  //       showStore: false,
  //     });
  //   } else {
  //     this.setData({
  //       chooseStore: item.currentTarget.dataset.item,
  //       showStore: false,
  //       even_true: false,
  //     });
  //   }
  // },
  // 工作时间弹窗 （默认）
  addDefaultTime() {
    this.setData({
      showDefault: true,
      isDefault: 1,
    });
  },
  showDefaultCloseBtn(e) {
    let {
      v
    } = e.target.dataset || e.currentTarget.dataset
    this.setData({
      [v]: false,
    });
  },
  // 添加工作时间 （按天—）
  addTime(e) {
    if(this.data.aplly_for!==-1){
      this.setData({
        showDay: true,
        isDefault: 2,
      });
    }
  },
  // 编辑工作时间弹窗
  editTime(e) {
    let item = e.currentTarget.dataset.item;
    if (item) {
      if (item.work_hour_start) {
        this.setData({
          choose_start: item.work_hour_start,
          choose_end: item.work_hour_end,
          isDefault: 0,
          period_id: item.id,
        });
      }
    }

    this.setData({
      show1: true,
      showDay: false,
      showDefault: false,
    });
  },
  bindTimeChange(e) {
    this.setData({
      choose_start: e.detail.value,
    });
  },
  bindTimeEndChange(e) {
    this.setData({
      choose_end: e.detail.value,
    });
  },
  delAll() {
    if(this.data.aplly_for==-1){
      return;
    }
    let today_time = new Date(`${this.data.today} 00:00:00`).getTime() / 1000;
    let json = {
      aid: this.data.aid,
      date: today_time
    }

    app._getNetWork({
      url: app.getNetAddresss("plugin.be-within-call.frontend.work-time.day-del"),
      data: json,
      success: resdata => {
        let {
          result,
          msg
        } = resdata.data;
        app.tips(msg);
        if (result) {
          this.getTimeList(today_time);
          this.set_calender();
        }
      }
    })
  },
  // 确认提交时间
  submitTime(e) {
    let json = {
      aid: this.data.aid,
      start_at: new Date(`${this.data.today} ${this.data.choose_start}:00`).getTime() / 1000,
      finish_at: new Date(`${this.data.today} ${this.data.choose_end}:00`).getTime() / 1000,
    };
    let url = "";
    if (this.data.isDefault === 1) {
      // 添加默认事件
      url = "plugin.be-within-call.frontend.work-time.add-default";
    } else if (this.data.isDefault == 2) {
      // 按天添加时间
      url = "plugin.be-within-call.frontend.work-time.create";
    }
    let urlStr = app.getNetAddresss(url);
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result == 1) {
          this.setData({
            show1: false,
            choose_start: "",
            choose_end: "",
          });
          if (this.data.isDefault === 1) {
            this.getDefault();
          } else {
            this.getTimeList(new Date(`${this.data.today} 00:00:00`).getTime() / 1000);
            this.set_calender()
          }
        }
      },
    });
  },
  //删除、添加时间重新复制子组件数据
  set_calender() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.be-within-call.frontend.work-time.group'),
      data: {
        aid: this.data.aid
      },
      success: resdata => {
        let {
          result,
          data,
          msg
        } = resdata.data;
        if (result) {
          let list = data;
          let lis = [];
          list.forEach(item => {
            lis.push(this.timestampToTime(item.date));
          });
          let mycomponent = this.selectComponent("#mycomponent");
          mycomponent.refresh(lis)
        } else {
          app.tips(msg);
        }
      }
    })

  },
  // 删除默认工作时间
  deleteTime(e) {
    let {id:wid} = e.currentTarget.dataset.date;
    app._postNetWork({
      url:app.getNetAddresss("plugin.be-within-call.frontend.work-time.del"),
      data:{wid},
      success:resdata=>{
        let {result,msg} = resdata.data;
        app.tips(msg);
        if(result){
          this.getDefault();
        }
      }
    })

  },
  changeStatus(e) {
    let need_rest = e.detail ? "0" : "1";
    let {id:wid} = e.currentTarget.dataset.item;
    let urlStr = app.getNetAddresss(
      "plugin.be-within-call.frontend.work-time.rest"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        wid,
        need_rest
      },
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result == 1) {
          this.getTimeList(new Date(`${this.data.today} 00:00:00`).getTime() / 1000);
        }
      },
    });
  },
  // 上班休息状态
  changeDayStatus(e) {
    console.log(e, "ee=====");
    let urlStr = app.getNetAddresss(
      "plugin.be-within-call.frontend.work-time.rest"
    );
    let date = new Date(`${this.data.today} 00:00:00`).getTime() / 1000
    app._getNetWork({
      url: urlStr,
      data: {
        date,
        aid: this.data.aid,
        need_rest: e.detail ? '0' : '1',
      },
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result == 1) {
          this.getData();
          this.getTimeList(date);
        }
      },
    });
  },
  /**
   *
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  // 日历组件点击事件
  select(e) {
    let touchDay = e.detail.work_date;
    this.setData({
      today: touchDay,
    });
    this.getTimeList(new Date(`${touchDay} 00:00:00`).getTime() / 1000);
  },

  getDefault() {
    app._getNetWork({
      url: app.getNetAddresss("plugin.be-within-call.frontend.work-time.date-time"),
      data: {
        aid: this.data.aid,
        date: 0
      },
      success: resdata => {
        let {
          result,
          msg,
          data
        } = resdata.data;
        if (result) {
          let arr = data;
          arr.forEach((item) => {
            item.work_hour_start = item.start_at;
            item.work_hour_end = item.finish_at;
          })
          let default_time = arr.filter(item => {
            if (item.date == 0) {
              return item;
            }
          })
          this.setData({
            default_time
          })
        } else {
          app.tips(msg);
        }
      }
    })
  },
});